package easier.app.x.result;

import android.os.Bundle;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * 简化resultApi使用
 *
 * @param <I> input
 * @param <O> output
 */
public class ResultFragment< I, O > extends Fragment {

    /**
     * 构造器
     */
    protected Builder< I, O > mBuilder;

    /**
     * @param builder 创建实例
     * @param <I>     输入
     * @param <O>     输出
     *
     * @return 类
     */
    public static < I, O > ResultFragment< I, O > newInstance( Builder< I, O > builder ) {

        ResultFragment< I, O > resultFragment = new ResultFragment<>();
        resultFragment.mBuilder = builder;
        return resultFragment;
    }

    public ResultFragment() {

    }

    @CallSuper
    @Override
    public void onCreate( @Nullable Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );

        /* 必须在创建时调用,否则异常 */
        try {
            registerForActivityResult( mBuilder.createContract(), new ActivityResultCallback< O >() {
                @Override
                public void onActivityResult( O result ) {

                    try {
                        if ( mBuilder.getResultCallback() != null ) {
                            mBuilder.getResultCallback().onActivityResult( result );
                        }
                    } catch ( Exception e ) {
                        e.printStackTrace();
                    } finally {
                        getParentFragmentManager().beginTransaction().remove( ResultFragment.this ).commit();
                    }
                }
            } ).launch( mBuilder.createInput() );
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    /**
     * 构造器
     *
     * @param <I> 输入
     * @param <O> 输出
     */
    public interface Builder< I, O > {

        /**
         * @return 创建约定
         */
        ActivityResultContract< I, O > createContract();

        /**
         * @return 创建回调
         */
        ActivityResultCallback< O > getResultCallback();

        /**
         * @return 创建input
         */
        I createInput();
    }
}